package com.ishare.common.service.base.impl;

import com.ishare.common.constant.GlobalReturnCode;
import com.ishare.common.dao.UserDao;
import com.ishare.common.entity.User;
import com.ishare.common.service.base.UserService;
import com.ishare.common.utils.MyBeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author 李嘉宾
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public User getUserById(Integer userId) {
        return userDao.findById(userId).orElse(null);
    }

    @Override
    public User getUserByUserName(String userName) {
        return userDao.findOne(Example.of(User.builder().username(userName).build())).orElse(null);
    }

    @Override
    public User getUserByEmail(String email) {
        return userDao.findOne(Example.of(User.builder().email(email).build())).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User insertUser(User saveUser) {
        if (saveUser.getCreateTime() == null) {
            saveUser.setCreateTime(System.currentTimeMillis());
        }
        saveUser.setUpdateTime(System.currentTimeMillis());
        return userDao.save(saveUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User updateUser(User updateUser) {
        updateUser.setUpdateTime(System.currentTimeMillis());
        User userById = getUserById(updateUser.getId());
        if (userById == null) {
            //用户为空
            throw GlobalReturnCode.SYSTEM_ERROR.createException();
        }
        return userDao.save(userById);
    }
}
